package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.editorModule.views.popUps.SaveAsPopUp;
	import example.documentbased.mainModule.controller.ICommonController;
	import example.documentbased.mainModule.models.vo.EditorVO;
	
	import flash.events.Event;
	
	import mx.utils.ObjectUtil;
	
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	import org.etherframework.controller.common.PopUpModel;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class ChangeEditorNameCommand extends ReactiveCommand
	{
		private var _editor:EditorVO;
		private var _editorModel:EditorModuleModel;
		private var _commonController:ICommonController;
		private var _editorController:IEditorController;
		
		public function ChangeEditorNameCommand(editorModel:EditorModuleModel, 
												commonController:ICommonController, 
												editorController:IEditorController)
		{
			_editorModel = editorModel;
			_commonController = commonController;
			_editorController = editorController;
			
			markAsInitialized();
		}
		
		public function initialize(editor:EditorVO):IReactiveCommand
		{
			_editor = editor;
			
			return this;
		}
		
		override public function observable():IObservable
		{
			var popUpModel:PopUpModel = new PopUpModel("Change Name", _editor.name);
			
			return _commonController.getShowPopUpCommand(SaveAsPopUp, popUpModel).observable()
			.mapMany(function(event:Event):IObservable
			{
				if (event.type == Event.COMPLETE)
				{
					var newName:String = SaveAsPopUp(popUpModel.popUp).editedName;
					var update:EditorVO = ObjectUtil.clone(_editor) as EditorVO;
					update.name = newName;
					
					return _editorController.getSaveEditorCommand(update).observable();
				}
				
				return Observable.value(new Unit());
			});
		}
	}
}